package com.north.light.libmusiccontroller.impl;

import android.app.Application;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;

import com.north.light.libmusiccontroller.MusicStatus;
import com.north.light.libmusiccontroller.bean.MusicPlayInfo;
import com.north.light.libmusiccontroller.bean.MusicPlayObj;
import com.north.light.libmusiccontroller.listener.MusicEventListener;
import com.north.light.libmusiccontroller.listener.MusicProgressListener;
import com.north.light.libmusiccontroller.utils.MusicStringUtils;
import com.north.light.musiclibrary.aidl.listener.LibPlayMusicOnPlayerEventListener;
import com.north.light.musiclibrary.aidl.model.LibPlayMusicSongInfo;
import com.north.light.musiclibrary.cache.LibPlayMusicCacheConfig;
import com.north.light.musiclibrary.constans.LibPlayMusicState;
import com.north.light.musiclibrary.manager.LibPlayMusicMusicLibrary;
import com.north.light.musiclibrary.manager.LibPlayMusicMusicManager;
import com.north.light.musiclibrary.notification.LibPlayMusicNotificationCreater;

import java.util.concurrent.CopyOnWriteArrayList;

/**
 * author:li
 * date:2022/10/16
 * desc:三方sdk impl
 */
public class MusicStarryOldImpl implements MusicControllerOldApi {

    private final CopyOnWriteArrayList<MusicEventListener> mEventListener = new CopyOnWriteArrayList<>();
    private final CopyOnWriteArrayList<MusicProgressListener> mProgressListener = new CopyOnWriteArrayList<>();

    private boolean mHadInit = false;

    //进度条更新
    private static final int HANDLER_PROGRESS = 0x0001;
    private static final long HANDLER_PROGRESS_INTERVAL = 1000;

    private LibPlayMusicMusicLibrary musicLibrary;

    private Handler mUIHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case HANDLER_PROGRESS:
                    try {
                        if (LibPlayMusicMusicManager.isPlaying()) {
                            long duration = LibPlayMusicMusicManager.get().getDuration();
                            long progress = LibPlayMusicMusicManager.get().getProgress();
                            long buffered = LibPlayMusicMusicManager.get().getBufferedPosition();
                            LibPlayMusicSongInfo songInfo = LibPlayMusicMusicManager.get().getCurrPlayingMusic();
                            String songUrl = null;
                            if (songInfo != null) {
                                songUrl = songInfo.getSongUrl();
                            }
                            notifyProgress(songUrl, progress, buffered, duration);
                            Log.d("MusicStarryImpl", "progress:  " + songUrl + " pro: " + progress + " buff: " + buffered + " duration: " + duration);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    mUIHandler.sendEmptyMessageDelayed(HANDLER_PROGRESS, HANDLER_PROGRESS_INTERVAL);
                    break;
            }
        }
    };

    @Override
    public void init(Application application) {
        mUIHandler.removeCallbacksAndMessages(null);
//        LibPlayMusicNotificationCreater creater = new LibPlayMusicNotificationCreater.Builder()
//                .setTargetClass("com.example.ktdemo.musicplayer.MusicPlayerTestActivity")
//                .setCreateSystemNotification(false)
//                .setNotificationCanClearBySystemBtn(false)
//                .build();
        //边播边存配置
        LibPlayMusicCacheConfig cacheConfig = new LibPlayMusicCacheConfig.Builder()
                .setOpenCacheWhenPlaying(true)
                .setCachePath(application.getExternalCacheDir().getAbsolutePath() + "/audio/")
                .build();

        musicLibrary = new LibPlayMusicMusicLibrary.Builder(application)
                .setNotificationCreater(null)
                .setCacheConfig(cacheConfig)
                .setAutoPlayNext(true)
                .build();
        musicLibrary.startMusicService();
        initListener();
    }

    /**
     * 歌曲信息转换
     */
    private MusicPlayInfo trainSongInfo(MusicStatus status) {
        LibPlayMusicSongInfo songInfo = LibPlayMusicMusicManager.get().getCurrPlayingMusic();
        if (songInfo == null) {
            return null;
        }
        long duration = LibPlayMusicMusicManager.get().getDuration();
        long progress = LibPlayMusicMusicManager.get().getProgress();
        MusicPlayInfo result = new MusicPlayInfo();
        result.setDuration(duration);
        result.setProgress(progress);
        result.setStatus(status);
        MusicPlayObj playObj = new MusicPlayObj();
        playObj.setPlayUrl(songInfo.getSongUrl());
        playObj.setAuthor(songInfo.getArtist());
        playObj.setCover(songInfo.getSongCover());
        playObj.setTitle(songInfo.getSongName());
        result.setInfo(playObj);
        return result;
    }

    private void initListener() {
        LibPlayMusicMusicManager.get().clearPlayerEventListener();
        LibPlayMusicMusicManager.get().addPlayerEventListener(new LibPlayMusicOnPlayerEventListener() {
            @Override
            public void onMusicSwitch(LibPlayMusicSongInfo music) {
                MusicPlayInfo result = trainSongInfo(MusicStatus.TYPE_SWITCH);
                if (result == null) {
                    return;
                }
                //数据回调
                notifyStatus(result);
            }

            @Override
            public void onPlayerStart() {
                MusicPlayInfo result = trainSongInfo(MusicStatus.TYPE_PLAYING);
                if (result == null) {
                    return;
                }
                //数据回调
                notifyStatus(result);
            }

            @Override
            public void onPlayerPause() {
                MusicPlayInfo result = trainSongInfo(MusicStatus.TYPE_PAUSE);
                if (result == null) {
                    return;
                }
                //数据回调
                notifyStatus(result);
            }

            @Override
            public void onPlayCompletion(LibPlayMusicSongInfo songInfo) {
                MusicPlayInfo result = trainSongInfo(MusicStatus.TYPE_PAUSE);
                if (result == null) {
                    return;
                }
                //数据回调
                notifyStatus(result);
            }

            @Override
            public void onPlayerStop() {
                MusicPlayInfo result = trainSongInfo(MusicStatus.TYPE_PAUSE);
                if (result == null) {
                    return;
                }
                //数据回调
                notifyStatus(result);
            }

            @Override
            public void onError(String errorMsg) {
                MusicPlayInfo result = trainSongInfo(MusicStatus.TYPE_ERROR);
                if (result == null) {
                    return;
                }
                //数据回调
                notifyStatus(result);
            }

            @Override
            public void onAsyncLoading(boolean isFinishLoading) {
                MusicPlayInfo result = trainSongInfo(MusicStatus.TYPE_BUFFERING);
                if (result == null) {
                    return;
                }
                //数据回调
                notifyStatus(result);
            }
        });
        //开始进度条回调handler
        mUIHandler.sendEmptyMessageDelayed(HANDLER_PROGRESS, HANDLER_PROGRESS_INTERVAL);
        mHadInit = true;
    }

    @Override
    public void release() {
        if (!hadInit()) {
            return;
        }
        LibPlayMusicMusicManager.get().stopMusic();
        LibPlayMusicMusicManager.get().reset();
    }

    @Override
    public void play(MusicPlayObj music) {
        if (!hadInit()) {
            return;
        }
        if (!checkPlayObj(music)) {
            return;
        }
        //执行播放逻辑
        LibPlayMusicSongInfo starrySongInfo = new LibPlayMusicSongInfo();
        //播放Url
        starrySongInfo.setSongUrl(music.getPlayUrl());
        starrySongInfo.setSongId(music.getPlayUrl());
        //封面
        starrySongInfo.setSongCover(MusicStringUtils.trainNoNull(music.getCover()));
        //作者
        starrySongInfo.setArtist(MusicStringUtils.trainNoNull(music.getAuthor()));
        //标题
        starrySongInfo.setSongName(MusicStringUtils.trainNoNull(music.getTitle()));
        LibPlayMusicMusicManager.get().playMusicByInfo(starrySongInfo);
    }

    @Override
    public void autoPlay(MusicPlayObj music) {
        if (!hadInit()) {
            return;
        }
        if (!checkPlayObj(music)) {
            return;
        }
        MusicPlayInfo musicPlayInfo = getCurrentInfo();
        if (musicPlayInfo == null || musicPlayInfo.getInfo() == null) {
            //首次播放
            play(music);
            return;
        }
        //再次播放，对比Url
        String playUrl = musicPlayInfo.getInfo().getPlayUrl();
        String targetUrl = music.getPlayUrl();
        if (playUrl.equals(targetUrl)) {
            //同一个音频
            if (isPlaying()) {
                pause();
            } else {
                resume();
            }
            return;
        }
        //不同音频
        play(music);
    }

    @Override
    public void pause() {
        if (!hadInit()) {
            return;
        }
        LibPlayMusicMusicManager.get().pauseMusic();
    }

    @Override
    public void resume() {
        if (!hadInit()) {
            return;
        }
        LibPlayMusicMusicManager.get().resumeMusic();
    }

    @Override
    public void stop() {
        if (!hadInit()) {
            return;
        }
        LibPlayMusicMusicManager.get().stopMusic();
    }

    @Override
    public void seekTo(long duration, boolean playWhenPause) {
        if (!hadInit()) {
            return;
        }
        LibPlayMusicMusicManager.get().seekTo((int) duration);
    }

    @Override
    public boolean checkPlayObj(MusicPlayObj musicPlayObj) {
        if (musicPlayObj == null) {
            return false;
        }
        if (TextUtils.isEmpty(musicPlayObj.getPlayUrl())) {
            return false;
        }
        return true;
    }

    @Override
    public boolean hadInit() {
        return mHadInit;
    }

    /**
     * public final static int STATE_IDLE = 1; //空闲
     * public final static int STATE_ASYNC_LOADING = 2; //加载中
     * public final static int STATE_PLAYING = 3; //播放中
     * public final static int STATE_PAUSED = 4; //暂停
     * public final static int STATE_ERROR = 5; //播放错误
     * public final static int STATE_STOP = 6; //停止
     */
    @Override
    public MusicPlayInfo getCurrentInfo() {
        if (!hadInit()) {
            return null;
        }
        int status = LibPlayMusicMusicManager.get().getStatus();
        switch (status) {
            case LibPlayMusicState.STATE_IDLE:
                return trainSongInfo(MusicStatus.TYPE_IDLE);
            case LibPlayMusicState.STATE_ASYNC_LOADING:
                return trainSongInfo(MusicStatus.TYPE_BUFFERING);
            case LibPlayMusicState.STATE_PLAYING:
                return trainSongInfo(MusicStatus.TYPE_PLAYING);
            case LibPlayMusicState.STATE_PAUSED:
                return trainSongInfo(MusicStatus.TYPE_PAUSE);
            case LibPlayMusicState.STATE_ERROR:
                return trainSongInfo(MusicStatus.TYPE_ERROR);
            case LibPlayMusicState.STATE_STOP:
                return trainSongInfo(MusicStatus.TYPE_PAUSE);
            default:
                return trainSongInfo(MusicStatus.TYPE_IDLE);
        }
    }

    @Override
    public boolean isPlaying() {
        return LibPlayMusicMusicManager.isPlaying();
    }


    @Override
    public boolean isIdle() {
        return LibPlayMusicMusicManager.isIdea();
    }

    @Override
    public boolean isPause() {
        return LibPlayMusicMusicManager.isPaused();
    }

    @Override
    public long getProgress() {
        if (!hadInit()) {
            return 0;
        }
        return LibPlayMusicMusicManager.get().getProgress();
    }

    @Override
    public long getDuration() {
        if (!hadInit()) {
            return 0;
        }
        return LibPlayMusicMusicManager.get().getDuration();
    }

    @Override
    public void setMusicStatusListener(MusicEventListener musicStatusListener) {
        if (musicStatusListener == null) {
            return;
        }
        mEventListener.add(musicStatusListener);
    }

    @Override
    public void removeMusicStatusListener(MusicEventListener musicStatusListener) {
        if (musicStatusListener == null) {
            return;
        }
        mEventListener.remove(musicStatusListener);
    }

    @Override
    public void setMusicProgressListener(MusicProgressListener progressListener) {
        if (progressListener == null) {
            return;
        }
        mProgressListener.add(progressListener);
    }

    @Override
    public void removeMusicProgressListener(MusicProgressListener progressListener) {
        if (progressListener == null) {
            return;
        }
        mProgressListener.remove(progressListener);
    }

    /**
     * 通知外部状态更新
     */
    private void notifyStatus(MusicPlayInfo info) {
        if (mEventListener.size() == 0 || info == null) {
            return;
        }
        for (MusicEventListener eventListener : mEventListener) {
            eventListener.status(info);
        }
    }

    /**
     * 通知外部进度条更新
     */
    private void notifyProgress(String url, long progress, long buffered, long duration) {
        if (mProgressListener.size() == 0) {
            return;
        }
        for (MusicProgressListener progressListener : mProgressListener) {
            progressListener.progressInfo(url, progress, buffered, duration);
        }
    }
}
